from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from django.http import HttpResponse
from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
from rest_framework.generics import GenericAPIView
from . import serializers
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
import logging
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.

logger=logging.getLogger('django')

# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    '''发送短信'''
    # 指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self,request,mobile):
        # 接受参数:mobile ,image_code_id,text
        # 校验参数:image_code_id,text
        # 对比text和服务器存储的图片验证码内容

        # 创建序列化器对象
        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成随机短信验证码
        sms_code="%06d"%random.randint(0,999999)
        logger.info(sms_code)

        # 发送短信验证码
        # 此处的发送短信是耗时的操作,不能阻塞后续的业务逻辑,所以需要异步的进行短信发送
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],1)

        # 异步发送短信验证码
        # 将延时任务,添加到任务队列,并触发异步任务,让worker可以观察到
        send_sms_code.delay(mobile,sms_code)

        # 存储短信验证码
        redis_conn=get_redis_connection('verify_codes')
        # redis_conn.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # # 存储是否60s重复发送短信
        # redis_conn.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)

        # 使用管道,让redis的多个指令只需要访问一次redis数据库,就可以一次执行完多个指令
        pl=redis_conn.pipeline()

        # 存储短信验证码
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 存储是否60s重复发送短信
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 注意:记得一定要调用execute()
        pl.execute()

        # 响应短信验证码
        return Response({'message':'OK'})




# url:'^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()
class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        '''提供图片验证码'''
        # 生成图片验证码
        text,image=captcha.generate_captcha()
        logger.info(text)

        # 将图片验证码的内容存储到redis中
        redis_conn=get_redis_connection("verify_codes")
        redis_conn.setex("img_%s"%image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        # 将图片响应给用户
        return HttpResponse(image,content_type='images/jpg')

